<!-- 新增和编辑弹窗 -->
<template>
  <a-modal
    :width="600"
    :visible="visible"
    :confirm-loading="loading"
    :title="isUpdate ? '修改轮播图' : '新建轮播图'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      layout="horizontal"
      ref="form"
      :model="form"
      :rules="rules"
      :label-col="{ md: { span: 8 }, sm: { span: 24 } }"
      :wrapper-col="{ md: { span: 16 }, sm: { span: 24 } }"
    >
      <a-row>
        <a-col :span="12">
          <a-form-item label="标题:" name="title">
            <a-input v-model:value="form.title" placeholder="请输入标题" allow-clear autocomplete="off"
                     size="large" />
          </a-form-item>
          <a-form-item label="排序:" name="dataSort">
            <a-input-number v-model:value="form.dataSort" placeholder="请输入排序" allow-clear autocomplete="off"
                            max="100" size="large" style="width: 100%" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="形象图:" name="imageFileId">
            <a-upload
              accept="image/png,image/jpeg"
              :headers="headers"
              action="/api/sysFileInfo/upload?secretFlag=N"
              list-type="picture-card"
              v-model:file-list="fileList"
              @preview="handlePreview"
            >
              <div v-if="fileList.length < 1">
                <slot name="icon">
                  <PlusOutlined class="ele-image-upload-icon" />
                </slot>
              </div>
            </a-upload>
            <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
              <img alt="example" style="width: 100%;margin-top: 10px" :src="previewImage" />
            </a-modal>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>

<script>
import { BannerApi } from '@/api/BannerApi';
import setting from '@/config/setting';

export default {
  name: 'PositionEdit',
  emits: ['done', 'update:visible'],
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object
  },

  data() {

    let picRule = async (rule, value) => {
      if (!value) {
        if (this.fileList.length === 0) {
          return Promise.reject('请上传形象图');
        }
      }
    };

    return {
      // 表单数据
      form: Object.assign({}, this.data),
      // 表单验证规则
      rules: {
        title: [{ required: true, message: '请输入标题', type: 'string', trigger: 'blur' }],
        dataSort: [{ required: true, message: '请输入排序(数值类型)', type: 'integer', trigger: 'blur' }],
        imageFileId: [{ required: true,validator: picRule, message: '请上传形象图', trigger: 'change' }],
        //manualFileId: [{ required: true, message: '请上传使用手册', trigger: 'change' }],
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      // 上传文件列表
      fileList: [],
      // 上传图片时候的header
      headers: {
        Authorization: setting.takeToken()
      },
      // 是否可以预览
      previewVisible: false,
      // 预览图片的地址
      previewImage: ''
    };
  },
  watch: {
    visible() {
      if (!this.data) {
        this.form = {};
        this.fileList = [];
      } else {
        this.form = Object.assign({}, this.data);
      }
      // 清空表单校验信息
      if (this.$refs.form) {
        this.$refs.form.clearValidate();
      }
    },
    data() {
      if (this.data) {
        this.form = Object.assign({}, this.data);
        //文件列表赋值
        this.isUpdate = true;
        // 拼接文件预览的url
        let token = setting.takeToken();
        this.fileList = [{
          name: '',
          url: `/api/sysFileInfo/public/preview?fileId=${this.data.imageFileId}&token=${token}`
        }];
      } else {
        // 新增-清除表格内容
        this.form = {};
        // 新增-文件列表内容
        this.fileList = [];
        this.isUpdate = false;
      }
      if (this.$refs.form) {
        this.$refs.form.clearValidate();
      }
    }
  },
  methods: {
  /*  async beforeUpload(file) {
      if (file.type !== 'image/jpeg'
        && file.type !== 'image/png'
        && file.type !== 'image/gif'
        && file.type !== 'image/jpg') {
        this.fileList = [];
        message.error('请上传图片文件!');
        return false;
      }
      return true;
    },*/

    /**
     * 保存和编辑职务
     */
    async save() {
      // 校验表单
      await this.$refs.form.validate();

      // 设置公司图片的id
      if (this.fileList.length > 0) {
        if (this.fileList[0]?.response) {
          this.form.imageFileId = this.fileList[0].response.data.fileId;
        }
      }

      // 修改加载框为正在加载
      this.loading = true;

      let result = null;

      // 执行编辑或修改
      if (this.isUpdate) {
        result = BannerApi.edit(this.form);
      } else {
        result = BannerApi.add(this.form);
      }
      result
        .then(result => {
          // 移除加载框
          this.loading = false;

          // 提示添加成功
          this.$message.success(result.message);

          // 如果是新增，则form表单置空
          if (!this.isUpdate) {
            this.form = {};
          }

          // 关闭弹框，通过控制visible的值，传递给父组件
          this.updateVisible(false);

          // 触发父组件done事件
          this.$emit('done');
        })
        .catch(() => {
          this.loading = false;
        });
    },

    /**
     * 更新编辑界面的弹框是否显示
     *
     * @param value true-显示，false-隐藏
     * @author fengshuonan
     * @date 2021/4/7 11:00
     */
    updateVisible(value) {
      this.$emit('update:visible', value);
    },
    /**
     * 点击预览图片时
     */
    handlePreview(file) {
      // 打开预览框
      this.previewVisible = true;
      // 获取到文件id
      let fileId = file?.response?.data?.fileId;
      if (!fileId) {
        // 拼接文件预览的url
        this.previewImage = file.url;
      } else {
        // 拼接文件预览的url
        let token = setting.takeToken();
        this.previewImage = `/api/sysFileInfo/public/preview?fileId=${fileId}&token=${token}`;
      }
    },

    /**
     * 点击取消按钮
     */
    handleCancel() {
      this.previewVisible = false;
    }
  }
};
</script>

<style scoped>
/*.ele-image-upload-icon {
  font-size: 22px;
  color: @text-color-secondary;
  opacity: 0.8;
}*/
</style>
